import { Input, ChangeDetectorRef, EventEmitter } from "@angular/core";
import { TemplateCriteriaModel } from "../../../../models/templateCriteria.model";
import { ReportingService } from "../../../../reporting.service";
import { Subscription, ReplaySubject } from "rxjs";
import { BaseComponent } from "../../../../../../shared/components/baseComponent/base.component";

export class BaseCriteriaTemplateComponent extends BaseComponent {
    private baseSub: Subscription;

    private loadSubject = new ReplaySubject<any>(1);
    public load = this.loadSubject.asObservable();

    public static changed: EventEmitter<boolean> = new EventEmitter();

    @Input() templateCriteria: TemplateCriteriaModel;

    @Input() edit: string;

    @Input() param: string;

    constructor(private baseService: ReportingService, private baseRef: ChangeDetectorRef) { 
        super(baseRef);
    }

    loadScoreData(fieldName: string): void {
        this.baseSub = this.baseService.details.subscribe(data => {
            if (data.hasOwnProperty(fieldName) && data[fieldName] != null) {
                for (var i = 0; i < data[fieldName].length; i++) {
                    if (data[fieldName][i].id == this.templateCriteria.id) {
                        //TODO: depending on the criteria type, get score or other fields                        
                        this.loadSubject.next(data[fieldName][i].score);
                        break;
                    }
                }
            } else
                this.loadSubject.next(undefined);
        });
    }

    loadIntervalData(minFieldName: string, maxFieldName: string): void {
        this.baseSub = this.baseService.details.subscribe(data => {
            this.loadSubject.next({ min: data[minFieldName] || 0, max: data[maxFieldName] || 0 });
        });
    }

    loadMultiSelectData(fieldName: string): void {
        this.baseSub = this.baseService.details.subscribe(data => {
            this.loadSubject.next(data[fieldName]);
        });
    }

    loadInvolvementData(): void {
        this.baseSub = this.baseService.details.subscribe(data => {
            this.loadSubject.next(data.typeFourCategories);
        });
    }

    ngOnDestroy() {
        if (this.baseSub)
            this.baseSub.unsubscribe();
    }
}